<?php

namespace App\Services\RewardGoldPrize;

use Carbon\Carbon;
use App\Models\User;
use App\Models\GoldRecord;
use App\Jobs\RewardFirstParentJob;
use Illuminate\Support\Facades\Log;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Database\Eloquent\Collection;

class RewardGoldPrize
{
	protected function reward()
	{
		GoldRecord::query()
			->whereNotNull('paid_at')
			->whereNull('rewarded_at')
			->whereDate('created_at', Carbon::yesterday())
			->chunks(50, function (Collection $records) {

				if ($records->isEmpty()) return false;

                /**
                 * @var GoldRecord $record
                 */
				foreach ($records as $record) {

                    if ($record->user->is_mock) continue;

					$queue = app()->environment('local') ? 'default' : 'default';
					dispatch(new RewardFirstParentJob($record))->onQueue($queue);

					Log::debug("Reward record: {$record->id} - user: {$record->user->id}");
				}

				return true;
			});
	}

    public function execute()
    {
        User::where('is_gold_intern', true)->update(['dividend_day' => 0]);

        $this->reward();
    }

	public function __invoke()
	{
		$this->execute();
		//Dinglog::text("========== Gold rewards paid ......");
	}
}
